package engine.systems.update.timer
{
	import engine.classes.enumerations.SystemPriority;
	import engine.systems.update.GameSystem;
	
	public class TimerSystem extends GameSystem
	{
		private var timer:Timer;
		private var i:int;
		private var data:TimerData;
		
		public function TimerSystem()
		{
			super(TimerNode, updateNode);
			
			this.priority = SystemPriority.UPDATE;
		}
		
		public function updateNode(node:TimerNode, time:Number):void
		{
			timer = node.timer;
			
			if(timer.paused) return;
			
			for(i = timer._data.length - 1; i >= 0; --i)
			{
				data = timer._data[i];
				
				if(data.paused) continue;
				
				if(data.delay > 0) data.delay -= time;
				else
				{
					data.time += time;
					
					while(data.time >= data.wait)
					{
						data.time -= data.wait;
						
						data.triggered.dispatch(node.entity);
						
						if(data.count > 0)
						{
							data.counter++;
							
							if(data.counter == data.count)
							{
								data.destroy();
								timer._data.splice(i, 1);
								break;
							}
						}
					}
				}
			}
		}
	}
}